﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace SharingCenter.Web.Classes
{
    public class NumericDropDownList : DropDownList
    {
        private int _lowerBound;
        private int _upperBound;
        private string _selected;
        private bool _isYear = false;

        public bool AddEmptyValueAtFirst { get; set; }
        public string EmptyValueItemText { get; set; }
        public bool SelectDefaultItem { get; set; }
        public string OnClientSelectionChanged { get; set; }


        public bool IsYearList { get { return this._isYear; } set { this._isYear = value; } }
        public int YearDifferenceForLowerBound { get; set; }

        public int DefaultSelectedYearFromThisYear { get; set; }

        public NumericDropDownList()
            : base()
        {
            this.Load += new EventHandler(NumericDropDownList_Load);
        }

        void NumericDropDownList_Load(object sender, EventArgs e)
        {
            _selected = null;
            FillDropDownList();
        }

        public int LowerBound 
        {
            get { return this._lowerBound; }
            set { this._lowerBound = value; }
        }

        public int UpperBound
        {
            get { return this._upperBound; }
            set
            {
                if (value >= this._lowerBound)
                {
                    this._upperBound = value;
                }
            }
        }

        void FillDropDownList()
        {
            if (_isYear)
            {
                _lowerBound = DateTime.Today.Year - YearDifferenceForLowerBound;
                _upperBound = DateTime.Today.Year;
                if (SelectDefaultItem)
                {
                    _selected = (DefaultSelectedYearFromThisYear == 0 ? _upperBound - 10 : _upperBound - DefaultSelectedYearFromThisYear).ToString();
                }
            }

            if (_lowerBound <= _upperBound)
            {
                ListItem li;
                string val;
                if (AddEmptyValueAtFirst)
                {
                    this.Items.Add(new ListItem(EmptyValueItemText, ""));
                }
                for (int i = _lowerBound; i <= _upperBound; i++)
                {
                    val = i.ToString();
                    li = new ListItem(val, val);
                    this.Items.Add(li);
                }
            }

            if (_selected != null)
            {
                this.Items.FindByValue(_selected).Selected = true;
            }
            
        }
    }
}
